<?php
/**
 * 基础备货国家skuFBA库存（EU备货国家）（库存来源：FBA仓）
 */
namespace App\Logic\SsBasicCountry;

use App\Models\SalesReport\FBAInventory;
use App\Models\SsBasic\CountrySkuStock;
use App\Models\SsBasic\CountryStockingSku;
use Illuminate\Support\Facades\DB;

class InitCountryFBAStock
{
    /**
     * 更新备货提货表中的FBA库存 (EU备货国家) （country:fba-stock）
     *
     * 运行时机：FBA库存报表,FBA收货报表有更新后
     * 设定：自定义运行
     */
    public static function exe(){
        try{
            //备货国家sku
            CountryStockingSku::query()
                ->orderBy('id')
                ->chunk(500, function ($countryStockingSkus){
                    DB::beginTransaction();
                    foreach ($countryStockingSkus as $stockingSku){
                        //erp-fba库存
                        $fbaInventory = FBAInventory::_getInventoryFind($stockingSku->country_id,$stockingSku->psku_id);
                        if($fbaInventory){
                            $instant = intval($fbaInventory->quantity) ?: 0;
                            $transit = intval($fbaInventory->inbound) ?: 0;
                        }else{
                            $instant = 0;
                            $transit = 0;
                        }

                        //备货国家sku
                        $stockingSku->fba_instant_num = $instant;
                        $stockingSku->fba_transit_num = $transit;
                        $stockingSku->save();
                        $stockingSku->over_stock = CountryStockingSku::getOverStock($stockingSku);
                        $stockingSku->over_stock_value = CountryStockingSku::getOverStockValue($stockingSku->over_stock, $stockingSku->unit_price);
                        $stockingSku->save();

                        //备货国家skuFBA库存
                        $skuStock = CountrySkuStock::query()->firstOrNew(['area_psku' => $stockingSku->area_psku]);
                        $skuStock->fba_instant_num = $instant;
                        $skuStock->fba_transit_num = $transit;
                        $skuStock->save();
                    }
                    DB::commit();
                });
        }catch (\Exception $e){
            DB::rollBack();
            report($e);
        }
    }

}
